# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
# esp.osdebug(None)
#import webrepl
# webrepl.start()
import utime
from machine import Pin
import network
import usocket as _socket
import ussl as ssl
import config


######
try:
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    count = 0
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(config.CONFIG['WIFI_SID'], config.CONFIG['WIFI_PW'])
        while (not wlan.isconnected()) and count < 10:
            utime.sleep(1)
            count = count+1
        print('network config:', wlan.ifconfig())
    ######
    use_stream = True
    s = _socket.socket()

    ai = _socket.getaddrinfo("www.baidu.com", 443)
    print("Address infos:", ai)
    addr = ai[0][-1]

    print("Connect address:", addr)
    s.connect(addr)

    s = ssl.wrap_socket(s)
    print(s)

    if use_stream:
        # Both CPython and MicroPython SSLSocket objects support read() and
        # write() methods.
        s.write(b"GET / HTTP/1.0\r\n\r\n")
        print(s.read(4096))
    else:
        # MicroPython SSLSocket objects implement only stream interface, not
        # socket interface
        s.send(b"GET / HTTP/1.0\r\n\r\n")
        print(s.recv(4096))

    s.close()
finally:
    if wlan is not None:
        wlan.disconnect()
        wlan.active(False)
######
